package leo.gptBot.gpt.tools;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @author ：Leo
 * @date ：Created in 2024/7/23 16:26
 * @description：
 */
@Component
@Slf4j
public class WeatherTool {
    @Value("${amap.api-key}")
    private String API_KEY;
    private static final HttpClient httpClient = HttpClient.newHttpClient();

    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Tool("This tool can help you get the weather.")
    public String getWeather(@P("the city to query")String city) throws IOException, InterruptedException {
        log.info("调用天气查询工具，查询城市: "+city);
        String adcode = getAdcode(city);
        return getWeatherInfo(adcode);
    }

    private String getAdcode(String city) throws IOException, InterruptedException {
        String url = String.format("https://restapi.amap.com/v3/config/district?keywords=%s&subdistrict=2&key=%s", city, API_KEY);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            JsonNode jsonNode = objectMapper.readTree(response.body());
            if (jsonNode.get("status").asText().equals("1")) {
                return jsonNode.get("districts").get(0).get("adcode").asText();
            }
        }
        return null;
    }
    private String getWeatherInfo(String adcode) throws IOException, InterruptedException {
        String url = String.format("https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=%s", adcode, API_KEY);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            JsonNode jsonNode = objectMapper.readTree(response.body());
            if (jsonNode.get("status").asText().equals("1")) {
                return jsonNode.toString();
            } else {
                log.error("无法获取天气信息: " + jsonNode.get("info").asText());
            }
        } else {
            log.error("请求失败，状态码: " + response.statusCode());
        }
        return null;
    }
}
